<template>
	<div class="system-menu-container">
		<div class="system-user-search mb15">
			<el-form :model="tableData.param.dataForm" :inline="true" ref="queryFormRef">
				<el-row>
					<el-col :span="8">
							<el-form-item label="编号" prop="tenantCode">
								<el-input v-model="tableData.param.dataForm.tenantCode" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
							<el-form-item label="名称" prop="tenantName">
								<el-input v-model="tableData.param.dataForm.tenantName" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="search">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="btnStyle">
			<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			<el-button type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
			<el-button type="primary" icon="ele-Edit" @click="setResEditHandle()" :disabled="dataListSelections.length !== 1">设置资源范围</el-button>
			<el-button type="primary" icon="ele-Edit" @click="orgManger()" :disabled="dataListSelections.length !== 1">机构权限管理</el-button>
			<el-button type="danger" icon="ele-Delete" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
		</div>
		<el-table :data="tableData.data" @selection-change="selectionChangeHandle" style="width: 100%">
			<el-table-column prop="id" type="selection" header-align="center" align="center" width="50"/>
			<el-table-column prop="tenantCode" label="编码" show-overflow-tooltip></el-table-column>
			<el-table-column prop="tenantName" label="名称" show-overflow-tooltip></el-table-column>
			<el-table-column label="操作" show-overflow-tooltip >
				<template #default="scope">
					<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
					<el-button type="primary" link @click="setResEditHandle(scope.row)">设置资源范围</el-button>
					<el-button type="primary" link @click="orgManger(scope.row)">机构权限管理</el-button>
					<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>

				</template>
			</el-table-column>
		</el-table>
		<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="tableData.param.page"
				background
				v-model:page-size="tableData.param.limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="tableData.total" small>
			</el-pagination>
		<el-dialog :close-on-click-modal="false" :title="!submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-form :model="submitForm" :rules="submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit" label-width="80px">
				<el-form-item label="编号" prop="tenantCode">
					<el-input v-model="submitForm.tenantCode" placeholder="编号" maxlength="50" v-bind:disabled="disabledInput"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="tenantName">
					<el-input v-model="submitForm.tenantName" placeholder="名称" maxlength="1000"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" ref="tenantMenuSet" v-model="tenantMenuSetVisible">
			<el-tree :data="treeTenantMenuList" ref="treeTenantMenu" node-key="id" :props="defaultProps1"  show-checkbox  :check-strictly="false"  :highlight-current="true">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="tenantMenuSetVisible = false">取消</el-button>
					<el-button type="primary" @click="saveTenantMenuSet">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, nextTick, defineComponent } from 'vue';
import type { FormInstance, ElTree } from 'element-plus'
import {systemApi} from '/@/api/systemapi'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
// 定义接口来定义对象的类型
interface TableDataRow {
	id: string
	tenantCode: string
	tenantName: string
}
interface TableDataState {
	tableData: {
		data: Array<TableDataRow>
		total: number
		loading: boolean
		param: {
			page: number
			limit: number
			dataForm: TableDataRow
		}
	}
	dataListSelections: Array<TableDataRow>
	addOrUpdateVisible: boolean
	tenantMenuSetVisible: boolean
	submitForm: TableDataRow
	disabledInput: boolean
	submitFormRule: any
	defaultProps1: {
		children: string
		label: string
	}
	treeTenantMenuList: any
	tenantResours: any
	checkTenantId: string
}

export default defineComponent({
	name: 'systemTenant',
	setup() {
		const router = useRouter();
		const state = reactive<TableDataState>({
			tableData: {
				data: [],
				total: 0,
				loading: false,
				param: {
					page: 1,
					limit: 10,
					dataForm: {
						id: '',
						tenantCode: '',
						tenantName: ''
					}
				}
			},
			dataListSelections: [],
			addOrUpdateVisible: false,
			tenantMenuSetVisible: false,
			submitForm: {
				id: '',
				tenantCode: '',
				tenantName: ''
			},
			disabledInput: true,
			submitFormRule: {
				tenantCode: { required: true, message: '请输入租户编号', trigger: 'blur' },
				tenantName: { required: true, message: '请输入租户名称', trigger: 'blur' }
			},
			defaultProps1: {
				children: 'childList',
				label: 'name'
			},
			treeTenantMenuList: [],
			tenantResours: [],
			checkTenantId: ''
		})
		const queryFormRef = ref<FormInstance>()
		const ruleFormRef = ref();
		const treeTenantMenu = ref<InstanceType<typeof ElTree>>()
		const search = () => {
			state.tableData.loading = true
			systemApi().getTenantList(state.tableData.param).then(data => {
				state.tableData.loading = false
				if (data && data.code === 0) {
					state.tableData.data = data.page.list
					state.tableData.total = data.page.totalCount
				} else {
					state.tableData.data = []
					state.tableData.total = 0
				}
			}).catch(() => {
				state.tableData.loading = false
			})
		}
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.tableData.param.page = 1
			search()
		}

		const addOrUpdateHandle = () => {
			state.addOrUpdateVisible = true
			state.disabledInput = false
			state.submitForm.id = ''
			state.submitForm.tenantCode = ''
			state.submitForm.tenantName = ''
		}
		const updateHandle = (row: TableDataRow | undefined) => {
			state.addOrUpdateVisible = true
			state.disabledInput = true
			if(!row){
				state.submitForm.id = state.dataListSelections[0].id
				state.submitForm.tenantCode = state.dataListSelections[0].tenantCode
				state.submitForm.tenantName = state.dataListSelections[0].tenantName
			} else {
				state.submitForm.id = row.id
				state.submitForm.tenantCode = row.tenantCode
				state.submitForm.tenantName = row.tenantName
			}
		}
		const deleteHandle = (id: string | undefined) => {
			var ids = id ? [id] : state.dataListSelections.map(item => {
				return item.id
			})
			if (!ids) {
				ElMessage.error('请选择记录！')
				return
			}
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				systemApi().deleteTenantInfo(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功')
						search();
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("删除失败")
				})
			})
		}
		const selectionChangeHandle = (val: Array<TableDataRow>) => {
			state.dataListSelections = val
		}
		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.tableData.param.limit = val;
			search()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.tableData.param.page = val;
			search()
		}
		// 页面加载时
		onMounted(() => {
			search()
		})

		const dataFormSubmit = () => {
			ruleFormRef.value.validate((valid: boolean) => {
				if (valid) {
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if(!state.submitForm.id) {
						//新增
						systemApi().saveTenantInfo(state.submitForm).then(data => {
							loading.close()
							if (data && data.code === 0) {
								state.addOrUpdateVisible = false
								search()
								ElMessage.success('保存成功')
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							loading.close()
							ElMessage.error("保存失败！")
						})
					} else {
						//修改
						systemApi().updateTenantInfo(state.submitForm).then(data => {
							loading.close()
							if (data && data.code === 0) {
								state.addOrUpdateVisible = false
								search()
								ElMessage.success('保存成功')
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							loading.close()
							ElMessage.error("保存失败！")
						})
					}
				} else {
					return false;
				}
			})
		}
		const setResEditHandle = (row: TableDataRow | undefined) => {
			if(!row){
				state.checkTenantId = state.dataListSelections[0].id
			} else {
				state.checkTenantId = row.id
			}
			state.tenantMenuSetVisible = true
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			systemApi().getSysTenantResTree(state.checkTenantId).then(data => {
				if (data) {
					state.treeTenantMenuList = data.tree
					state.tenantResours = data.asingRes
					nextTick(() => {
						checkStation(data.asingRes)
					})
				} else {
					state.treeTenantMenuList = []
				}
				loading.close()
			}).catch(() => {
				loading.close()
			})
		}
		const checkStation = (asingRes: any) => {
			if (asingRes) {
				var checkArrays = new Array()
				asingRes.forEach((item, index, arr) => {
					if (treeTenantMenu.value!.getNode(item.menuId)) {
						if (treeTenantMenu.value!.getNode(item.menuId).isLeaf) {
							checkArrays.push(item.menuId)
						}
					}
				})
				treeTenantMenu.value!.setCheckedKeys(checkArrays, false)
			} else {
				treeTenantMenu.value!.setCheckedKeys([], false)
			}
		}
		const saveTenantMenuSet = () => {
			ElMessageBox.confirm('是否确定保存', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				let checkResIds = treeTenantMenu.value!.getCheckedKeys()
				checkResIds = checkResIds.concat(treeTenantMenu.value!.getHalfCheckedKeys())
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().setSysTenantMenu(state.checkTenantId, checkResIds).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('设置成功')
						state.tenantMenuSetVisible = false
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("保存失败")
				}).finally(() => {
					loading.close()
				})
			})
		}
		const orgManger = (row: TableDataRow | undefined) => {
			if(!row){
				router.push({path: '/sys/org', query: {tenant: state.dataListSelections[0].id}}) 
			} else {
				router.push({path: '/sys/org', query: {tenant: row.id}})
			}
		}
		return {
			queryFormRef,
			ruleFormRef,
			search,
			reSetForm,
			addOrUpdateHandle,
			updateHandle,
			deleteHandle,
			selectionChangeHandle,
			onHandleSizeChange,
			onHandleCurrentChange,
			dataFormSubmit,
			setResEditHandle,
			treeTenantMenu,
			checkStation,
			saveTenantMenuSet,
			router,
			orgManger,
			...toRefs(state),
		}
	}
})
</script>

<style scoped>

</style>